package cn.com.dashihui.pay.refund;

import java.util.Date;

import org.apache.log4j.Logger;

import com.alipay.api.AlipayApiException;
import com.alipay.api.CertAlipayRequest;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import cn.com.dashihui.api.common.GroupCode;
import cn.com.dashihui.api.common.OrderCode;
import cn.com.dashihui.api.dao.Order;
import cn.com.dashihui.api.dao.OrderPayAPIRecord;
import cn.com.dashihui.api.dao.User;
import cn.com.dashihui.api.service.GroupbuyingService2;
import cn.com.dashihui.kit.CommonKit;
import cn.com.dashihui.kit.DatetimeKit;
import cn.com.dashihui.kit.DoubleKit;
import cn.com.dashihui.pay.wx.kit.HttpsRequest;
import cn.com.dashihui.pay.wx.kit.UtilKit;
import cn.com.dashihui.pay.wx.request.RefOrderReqData;
import cn.com.dashihui.pay.wx.response.RefOrderResData;

/**
 * 
 * @author Administrator
 *	
 */
public class Refund {
	private static Logger logger = Logger.getLogger(Refund.class);
	/**
	 * 支付宝退款
	 * @param orderNum 订单号
	 * @param amount 退款金额
	 * @param action 退款描述
	 * @return 0.退款成功1.退款未发送2.退款请求发送失败3.请求发送成功，但是退款失败
	 */
	public static int alipayRefund(String orderNum,Double amount,String action) {
		//支付宝
		String gateway=PropKit.get("applipay.url");
		String app_id=PropKit.get("appalipay.partner");
		String privateKey=PropKit.get("appalipay.privateKey");
		String charset=PropKit.get("applipay.charset");
		String sign_type=PropKit.get("applipay.signType");
		String app_cert_path=PathKit.getRootClassPath()+"/"+PropKit.get("applipay.appCertPublicKey");
		String alipay_cert_path=PathKit.getRootClassPath()+"/"+PropKit.get("applipay.alipayCertPublicKey");
		String alipay_root_cert_path=PathKit.getRootClassPath()+"/"+PropKit.get("applipay.alipayRootCert");
		//构造client
		CertAlipayRequest certAlipayRequest = new CertAlipayRequest();
		certAlipayRequest.setServerUrl(gateway);
		certAlipayRequest.setAppId(app_id);
		certAlipayRequest.setPrivateKey(privateKey);
		certAlipayRequest.setFormat("json");
		certAlipayRequest.setCharset(charset);
		certAlipayRequest.setSignType(sign_type);
		certAlipayRequest.setCertPath(app_cert_path);
		certAlipayRequest.setAlipayPublicCertPath(alipay_cert_path);
		certAlipayRequest.setRootCertPath(alipay_root_cert_path);
		String total_fee = String.valueOf(amount);
		DefaultAlipayClient alipayClient;
		try {
			alipayClient = new DefaultAlipayClient(certAlipayRequest);
			AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();//创建API对应的request类
			request.setBizContent("{" +
			"    \"out_trade_no\":\""+orderNum+"\"," +
			"    \"refund_reason\":\""+action+"\"," +
			"    \"refund_amount\":\""+total_fee+"\"" +
			
			"  }");//设置业务参数
			AlipayTradeRefundResponse response = alipayClient.certificateExecute(request);//通过alipayClient调用API，获得对应的response类
			System.out.println("支付宝退款请求响应："+response.getBody());
			if (response.isSuccess()) {//请求成功
				System.out.println("支付宝退款请求成功");
				//保存接口请求记录
				new OrderPayAPIRecord().set("orderNum", orderNum)
				.set("sendContent", request.getBizContent())
				.set("returnContent", response.getBody())
					.set("payMethod", 3)
					.set("flag", 4)
					.save();
				if("Success".equals(response.getMsg())){
					System.out.println("支付宝退款成功");
					return 0;
				}else {
					return 3;
				}
			}else {
				//发送退款请求失败
				return 2;
			}
		} catch (AlipayApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			//发送准备退款请求失败
			return 1;
		}
	}
	
	/**
	 * 余额退款
	 * @param orderNum 订单号
	 * @param user 用户
	 * @param addMoney 退款金额
	 * @param action 订单操作描述
	 * @return 0.退款成功4.修改用户余额失败5.用户余额记录更新失败
	 */
	
	public static int BALANCE1(String orderNum,User user,Double addMoney,String action) {
		//变化前金额
		Double oldMoney = user.getDouble("money");
		//变化后金额
		Double newMoney = DoubleKit.add(oldMoney, addMoney);
		
		Record re1 = new Record().set("userid", user.getInt("id"))
				.set("amount", addMoney)
				.set("type", "1")
				.set("fromOrderNum", orderNum)
				.set("createDate", new Date())
				.set("orderType", OrderCode.MoneyState.REORDER)
				.set("nowAmount", newMoney)
				.set("oldAmount", oldMoney)
				.set("describe", action);
		if(Db.update("UPDATE t_bus_user SET money = ? WHERE id = ?", newMoney,user.getInt("id"))==1){
			if(Db.save("t_bus_user_money", re1)){
				return 0;
			}else {
				return 5;
			}
		}else {
			return 4;
		}
	}
	
	
	/**
	 * 
	 * @param orderNum
	 * @param amount
	 * @param userid
	 * @return 0.退款成功1.退款未发送2.退款请求发送失败3.请求发送成功，但是退款失败
	 */
	public static int weiXinR(String orderNum,Double amount,int userid){
		String certpath = PathKit.getRootClassPath()+"/"+PropKit.get("weixinpay.open.cert");
		String certpassword = PropKit.get("weixinpay.mch_id");
		//付款方式为微信的退款
		System.out.println(">>>>>>>>>>>付款方式为   微信   的退款<<<<<<<<<<<<<<");
		//付款方式为微信的退款
		String out_refund_no = "TT"+DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS")+CommonKit.randomNum(3);
		String total_fee = String.valueOf(Double.valueOf(DoubleKit.mul(amount,100)).intValue()).toString();
		//向微信发起退款请求
		RefOrderReqData reOrderReqData = new RefOrderReqData(orderNum,out_refund_no,total_fee,total_fee, "取消订单退款");
		RefOrderResData reOrderRspData = null;
		try {
			reOrderRspData = (RefOrderResData)UtilKit.getObjectFromXML(new HttpsRequest(certpath,certpassword).post(PropKit.get("weixinpay.orderrefund"), reOrderReqData), RefOrderResData.class);
		}catch(Exception e){
			e.printStackTrace();
			System.out.println("Response....:"+reOrderReqData);
		}
		//预支付完成
		if(reOrderRspData!=null){
			System.out.println("Response....:"+reOrderReqData);
			//保存接口请求记录
			String sendContent = UtilKit.getXMLFromObject(reOrderReqData);
			String returnContent = UtilKit.getXMLFromObject(reOrderRspData);
			new OrderPayAPIRecord().set("orderNum", orderNum)
				.set("sendContent", sendContent)
				.set("returnContent", returnContent)
				.set("payMethod", 1)
				.set("flag", 4)
				.save();
			if(reOrderRspData.getReturn_code().equals("SUCCESS")&&reOrderRspData.getResult_code().equals("SUCCESS")){
				return 0;
			}else {
				return 3;
			}
		}else {
			return 2;
		}
	}
}
